package com.example.wan_android.viewmodel

import android.content.Intent
import android.util.Log
import android.widget.ImageView
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.wan_android.R
import com.example.wan_android.http.code.CollectionPaperRepository
import com.example.wan_android.http.code.UnCollectionRepository
import com.example.wan_android.http.code.UserRepository
import com.example.wan_android.model.ActJumpData
import com.example.wan_android.ui.activity.LoginActivity
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel() {
    val actJumpLiveData = MutableLiveData<ActJumpData>()
    protected val _isLogin = MutableLiveData<Boolean>(false)
    val isLogin = _isLogin
    open fun collection(index: Long) {
        viewModelScope.launch {
            CollectionPaperRepository().fetchCollectionList(index)
                .onSuccess {
//
                }
                .onFailure {
                    jumpLoginActivity()
                }
        }
    }

    open fun unCollection(index: Long) {
        viewModelScope.launch {
            UnCollectionRepository().fetchUnCollectionList(index)
                .onSuccess {
//
                }
                .onFailure {
                    jumpLoginActivity()
                }
        }
    }

    fun changeIcon(isCollection: Boolean, imageView: ImageView) {
        if (isCollection) {
            imageView.setImageResource(R.drawable.ic_collect)
        } else {
            imageView.setImageResource(R.drawable.ic_collected)
        }
    }

    fun login(username: String, password: String) {
        viewModelScope.launch {
            UserRepository().fetchLoginUserData(username, password).onSuccess {
                _isLogin.value = true
            }.onFailure {
                Log.e("TAG", "login: ${it.message}")
            }
        }
    }

    fun jumpLoginActivity() {
        startActivity(Intent(), targetClass = LoginActivity::class.java)
    }

    /**
     * 启动activity
     */
    @JvmOverloads
    protected fun startActivity(
        targetIntent: Intent? = null,
        targetClass: Class<*>,
        finishCurrent: Boolean = false,
    ) {
        actJumpLiveData.postValue(ActJumpData(targetIntent, targetClass, finishCurrent))
    }

    /**
     * 关闭activity
     */
    protected fun finishActivity() {
        actJumpLiveData.postValue(ActJumpData(null, null, true))
    }
}